package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.dto.SmsLoginParam;
import com.itheima.health.result.Result;
import com.itheima.health.service.PhoneLoginService;
import com.itheima.health.util.VerifyCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/mobile")
@Slf4j
public class PhoneLoginController {
    @Autowired
    private PhoneLoginService phoneLoginService;

    /**
     * 获取验证码
     * @param type
     * @param telephone
     * @return
     */
    @PostMapping("/validateCode/send")
    public Result validateCodeSend(String type,String telephone) {
        if (!StringUtils.isEmpty(telephone)) {
            //生成随机的4位验证码
            String code = VerifyCodeUtils.generateVerifyCode(4).toString();
            log.info("code={}", code);
            phoneLoginService.createPhoneUser(telephone,code);
            return new Result(true, MessageConst.ACTION_SUCCESS);
        }
            //redisTemplate.opsForValue().set(telephone, code);
        return new Result(true, MessageConst.ACTION_FAIL);
    }

    @PostMapping("/login/smsLogin")
    public Result smsLogin(@RequestBody SmsLoginParam smsLoginParam){
        SmsLoginParam user = phoneLoginService.findByTelephone(smsLoginParam.getTelephone());
        if (user != null){
            if (user.getValidateCode().equals(smsLoginParam.getValidateCode())){
                return new Result(true,MessageConst.LOGIN_SUCCESS);
            }
            return new Result(false,MessageConst.VALIDATECODE_ERROR);

        }


        return new Result(false,MessageConst.TELEPHONE_VALIDATECODE_NOTNULL);
    }

}
